import { defineStore } from 'pinia'
import router from '@/router'
import config from '@/config'
import http from '@/utils/http'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      token: localStorage.token,
    }
  },
  actions: {

    login(data) {
      http.post('login', data, {
        needLogin: false,
        showLoading: '登录中...',
      }).then((res) => {
        const route = router.currentRoute.value
        localStorage.token = res.data.token;
        this.token = res.data.token
        router.replace(route.query.backUrl)
      })
    },

    /**
     * 登录
     */
    reLogin() {
      // router.push({ name: 'Login', replace: true })
      this.token = null;
      localStorage.removeItem('token');
      let loginUrl = config.base + `/login?backUrl=` + encodeURIComponent(location.pathname + location.search);
      router.replace(loginUrl)
    },

    /**
     * 判断登录状态
     */
    checkLogin(route) {

      if (!route) route = router.currentRoute.value

      // 过滤免登陆页面
      const isFilter = [config.base + '/vod', config.base + '/login'].some(value => route.path.includes(value))
      if (isFilter) return;


      // 已有token，后台验证
      if (this.token) {
        http({
          url: '/user/check',
          method: 'post',
          needLogin: false,
          showLoading: false,
        })
      }
      // 无token，去登录
      else {
        this.reLogin()
      }
    }
  },
})
